package com.hackordie.daos;

import com.hackordie.commons.authorities.Role;
import com.hackordie.daos.mappers.RoleMapper;

public class RoleDao extends ACommonDao<Role> {

    @Override
    public boolean create(Role entity) {
        final String SQL = "INSERT INTO Roles (name, enabled) " +
        		           "VALUES ('" + entity.getName() + "', " + 
        		                         entity.isEnabled() + ")";
        
        if(jdbcTemplate.update(SQL) == 1) {
            return true;
        }        
        return false;
    }

    @Override
    public boolean delete(int id) {
        final String SQL = "DELETE FROM Roles WHERE idRole = " + id;
               
        if (jdbcTemplate.update(SQL) == 1) {
            return true;
        }
        return false;
    }

    @Override
    public boolean update(Role entity) {
        final String SQL = "UPDATE Roles " +
        		           "SET name = '" + entity.getName() + "', " + 
        		               "enabled = " + entity.isEnabled() +  " " +
        		           "WHERE idRole = " + entity.getId();
        
        if(jdbcTemplate.update(SQL) == 1) {
            return true;
        }
        return false;
    }

    @Override
    public Role[] getAll() {
        final String SQL = "SELECT * FROM Roles";
        return jdbcTemplate.query(SQL, new RoleMapper()).toArray(new Role[] {});      
    }

    @Override
    public Role get(int id) {
        final String SQL = "SELECT * FROM Roles WHERE idRole = ?";
        return jdbcTemplate.queryForObject(SQL, new RoleMapper(), id);       
    }
    
    public Role[] getByRange(int first, int last) {
        final String SQL = "SELECT * FROM roles LIMIT ?,?";
        return jdbcTemplate.query(SQL, new RoleMapper(), first, last).toArray(new Role[] {});
    }
    
    public int countAll() {
        final String SQL = "Select COUNT(idRole) FROM roles";
        return jdbcTemplate.queryForObject(SQL, Integer.class);
    }

    public Role get(String nameRole) {
        final String SQL = "SELECT * FROM Roles WHERE name = ?";
        return jdbcTemplate.queryForObject(SQL, new RoleMapper(), nameRole);   
    }
}